#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "config.h"

int main()
{
    int err;
    int s;
    
    s = socket(AF_INET, SOCK_DGRAM, 0);
    if (s < 0)
    {
        perror("socket()");
        exit(1);
    }

    struct sockaddr_in local_addr;
    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_port = htons(MCAST_PORT);
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    err = bind(s, (struct sockaddr *)&local_addr, sizeof(local_addr));
    if (err < 0)
    {
        perror("bind()");
        exit(1);
    }

    struct ip_mreq mreq;
    mreq.imr_multiaddr.s_addr = inet_addr(MCAST_ADDR);
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
    err = setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
    if (err < 0)
    {
        perror("setsockopt()");
        exit(1);
    }

    struct sockaddr_in send_addr;
    int send_addr_len = sizeof(send_addr);
    char buff[BUFF_SIZE] = { '\0' };
    while (1)
    {
        memset(buff, 0, BUFF_SIZE);
        err = recvfrom(s, buff, BUFF_SIZE, 0, (struct sockaddr *)&send_addr, &send_addr_len);
        if (err < 0)
        {
            perror("recvfrom()");
            close(s);
            exit(1);
        }

        printf("[Received from multicast] %s\n", buff);
    }

    close(s);

    return 0;
}